<?php
/**
 * 非Yii函数公共静态类库
 * @since 2011-8-22
 */
class Common {
	/**
	 * JS弹出对话框并跳转
	 * Enter description here ...
	 * @param $msg （提示信息内容）
	 * @param $url （跳转的URL地址）
	 */
	public static function jsalerturl($msg,$url=''){
		echo '<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />';
		if(empty($url)){
			echo "<script>alert('".$msg."');history.back();</script>";
		}else{
			echo "<script>alert('".$msg."');window.location='".$url."'</script>";
		}
		exit;
	}
	/**
	 * js弹出框
	 * Enter description here ...
	 * @param $msg （提示内容信息）
	 */
	public static function jsalert($msg){
		echo '<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />';
		echo "<script>alert('".$msg."');</script>";
		exit;
	}
	/**
	 * 匹配手机号码
	 * @author cilun
	 * @param $phone 手机号码
	 */
	public static function matchPhone ($phone = '') {
		if (!empty($phone)) {
			if (preg_match("/^(0|86|086|\+86|12520){0,1}(13[0-9]|147|15[0-9]|18[0-9])[0-9]{8}$/" , $phone)) {    
			    return true;
			} else {   
			    return false;
			}
		} else {
			return false;
		}
	}
	
	/**
	 * 匹配手机SIM号码
	 * @author cilun
	 * @param $sim 手机号码
	 */
	public static function matchSIM($sim = '') {
		if (!empty($sim)) {
			if (preg_match("/^[0-9]{15}$/" , $sim)) {   
			    return true;
			} else {   
			    return false;
			}
		} else {
			return false;
		}
	}
	
	/**
	 * 匹配参数是否为数字
	 * @author cilun
	 * @param $para 数字参数
	 */
	public static function matchNum($para = '') {
		if (!empty($para)) {
			if (preg_match("/^[0-9]+$/" , $para)) {   
			    return true;
			} else {   
			    return false;
			}
		} else {
			return false;
		}
	}
	
	/**
	 * 匹配是否为url
	 * @author cilun
	 * @param $para url参数
	 */
	public static function matchUrl($para = '') {
		if (!empty($para)) {
			if (preg_match("/^http:\/\/[A-Za-z0-9]+\.[A-Za-z0-9]+[\/=\?%\-&_~`@[\]\':+!]*([^<>\"\"])*$/" , $para)) {
			    return true;
			} else {   
			    return false;
			}
		} else {
			return false;
		}
	}
	
	/**
	 * 软件最新版本信息
	 * @author Star.Li
	 * @param $para 数字参数
	 */
	public static function getSoftVersion() {
		return '1.1';
	}
	
	
	/**
	 * 递归创建目录并赋权限
	 * @author cilun
	 * @param $dir 目录
	 */
	public static function makeDir($dir) {
		if (! is_dir ( $dir )) {
			if (! makeDir ( dirname ( $dir ) )) {
				return false;
			}
			if (! makeDir ( $dir, 0777 )) {
				return false;
			}
		}
		return true;
	}
	
	/**
	 * 调试信息放入txt
	 * @author cilun
	 * @param $txt 内容
	 */
	public static function debugTxt($txt) {
		$myfile = 'C:\\bugs.txt';
		$file_pointer = fopen($myfile,"a");
		fwrite($file_pointer,$txt);
		fclose($file_pointer);
	}
	
	/**
	 * 下载文件
	 * @author ciun
	 * @param $dir 目录文件
	 */
	public static function downLoad($params = '') {
		$file = $params['file'];
		
		$fsize = filesize($file);
	    // 截取文件扩展名
		$file_name = basename($params ['file']);
		$file_dir = isset ( $params ['file'] ) ? str_replace($file_name, '', $file) : '';
		$file = @fopen ( $file, "rb" );
		
	    $ext = explode(".", $params['file']);
	    $ext = strtolower(end($ext));
		switch($ext) {
	        case 'jar': $mime = "application/java-archive"; break;
	        case 'zip': $mime = "application/zip"; break;
	        case 'jpeg': $mime = "image/jpeg"; break;
	        case 'jpg': $mime = "image/jpg"; break;
	        case 'jad': $mime = "text/vnd.sun.j2me.app-descriptor"; break;
	        case "gif": $mime = "image/gif"; break;
	        case "png": $mime = "image/png"; break;
	        case "pdf": $mime = "application/pdf"; break;
	        case "txt": $mime = "text/plain"; break;
	        case "doc": $mime = "application/msword"; break;
	        case "ppt": $mime = "application/vnd.ms-powerpoint"; break;
	        case "wbmp": $mime = "image/vnd.wap.wbmp"; break;
	        case "wmlc": $mime = "application/vnd.wap.wmlc"; break;
	        case "mp4s": $mime = "application/mp4"; break;
	        case "ogg": $mime = "application/ogg"; break;
	        case "pls": $mime = "application/pls+xml"; break;
	        case "asf": $mime = "application/vnd.ms-asf"; break;
	        case "swf": $mime = "application/x-shockwave-flash"; break;
	        case "mp4": $mime = "video/mp4"; break;
	        case "m4a": $mime = "audio/mp4"; break;
	        case "m4p": $mime = "audio/mp4"; break;
	        case "mp4a": $mime = "audio/mp4"; break;
	        case "mp3": $mime = "audio/mpeg"; break;
	        case "m3a": $mime = "audio/mpeg"; break;
	        case "m2a": $mime = "audio/mpeg"; break;
	        case "mp2a": $mime = "audio/mpeg"; break;
	        case "mp2": $mime = "audio/mpeg"; break;
	        case "mpga": $mime = "audio/mpeg"; break;
	        case "wav": $mime = "audio/wav"; break;
	        case "m3u": $mime = "audio/x-mpegurl"; break;
	        case "bmp": $mime = "image/bmp"; break;
	        case "ico": $mime = "image/x-icon"; break;
	        case "3gp": $mime = "video/3gpp"; break;
	        case "3g2": $mime = "video/3gpp2"; break;
	        case "mp4v": $mime = "video/mp4"; break;
	        case "mpg4": $mime = "video/mp4"; break;
	        case "m2v": $mime = "video/mpeg"; break;
	        case "m1v": $mime = "video/mpeg"; break;
	        case "mpe": $mime = "video/mpeg"; break;
	        case "mpeg": $mime = "video/mpeg"; break;
	        case "mpg": $mime = "video/mpeg"; break;
	        case "mov": $mime = "video/quicktime"; break;
	        case "qt": $mime = "video/quicktime"; break;
	        case "avi": $mime = "video/x-msvideo"; break;
	        case "midi": $mime = "audio/midi"; break;
	        case "mid": $mime = "audio/mid"; break;
	        case "amr": $mime = "audio/amr"; break;
	        case "apk": $mime = "application/vnd.android.package-archive"; break;
	        case "sisx": $mime = "x-epoc/x-sisx-app"; break;
	        case "sis": $mime = "application/vnd.symbian.install"; break;
	        case "ipa": $mime = "application/iphone"; break;
	        default: $mime = "application/force-download";
	    }
	    if (ob_get_length() !== false) @ob_end_clean(); //清除以前的缓冲
		header("Pragma: public");
		header('Last-Modified: '.gmdate('D, d M Y H:i:s') . ' GMT');
		header('Cache-Control: no-store, no-cache, must-revalidate');
		header('Cache-Control: pre-check=0, post-check=0, max-age=0');
		header('Content-Description: File Transfer');
    	header('Content-Type: ' . $mime);
   		header('Content-Disposition: attachment; filename=' . $file_name);
		header("Content-Transfer-Encoding: binary" );
		header("Content-Length: $fsize");
		header("Expires: 0" );
		header('Content-Disposition: attachment; filename="' . $file_name .'"');
		while(!feof($file)) {
			echo fread($file,8192);
		}
		fclose ($file);
		@flush();
		@ob_flush();
	    
	}
	
	/**
	 * 取出空格 \r\n
	 * @param unknown_type $str
	 */
	function performstr($str) {
        $str=chop($str); //去掉连续空白
        $str=str_replace("<P></P>","",$str);//去掉<p></P>
        $str=str_replace("\r","",$str);//去掉\r
        $str=str_replace("\n","<br>",$str);//去掉\n
        $str=addslashes($str);//加入斜线
        return($str);
	}
	/***
	 * 过滤
	 */
  	public static function filter($str) {
	    $document = $str;
	    $search = array(
	        /*"'<script[^>]*?>.*?</script>'si",*/ // 去掉 javascript
	    	"/",
	        /*"'<style[^>]*?>.*?</style>'si", // 去掉 css
	        "'<[/!]*?[^<>]*?>'si", // 去掉 HTML 标记
	        "'<!--[/!]*?[^<>]*?>'si", // 去掉 注释标记
	        "'([rn])[s]+'", // 去掉空白字符
	        "'&(quot|#34);'i", // 替换 HTML 实体
	        "'&(amp|#38);'i",
	        "'&(lt|#60);'i",
	        "'&(gt|#62);'i",
	        "'&(nbsp|#160);'i",
	        "'&(iexcl|#161);'i",
	        "'&(cent|#162);'i",
	        "'&(pound|#163);'i",
	        "'&(copy|#169);'i",
	        "'&#(d+);'e"*/
	        ); // 作为 PHP 代码运行
	    $replace = array(//"",
	        "//",
	        /*"",
	        "",
	        "\1",
	        "\"",
	        "&",
	        "<",
	        ">",
	        " ",
	        chr(161),
	        chr(162),
	        chr(163),
	        chr(169),
	        "chr(\1)"*/);
	//$document为需要处理字符串，如果来源为文件可以
	//$document = file_get_contents('http://www.phpzixue.cn/');
	    $out = preg_replace($search, $replace, $document);
	    return $out;
	}
	public static function helper(){
		return new Helper();
		
	}
	public static function getPhone ($phone = '') {
		$phone = str_replace("-", '', trim($phone));
		$phone = strrev($phone);
		return strrev(substr($phone,0,11));
	}
	static function authcode($string, $operation = 'DECODE', $key = 'fzd2012', $expiry = 0) {
	    // 动态密匙长度，相同的明文会生成不同密文就是依靠动态密匙
	    // 加入随机密钥，可以令密文无任何规律，即便是原文和密钥完全相同，加密结果也会每次不同，增大破解难度。
	    // 取值越大，密文变动规律越大，密文变化 = 16 的 $ckey_length 次方
	    // 当此值为 0 时，则不产生随机密钥
	    $ckey_length = 4;
	
	    // 密匙
	    $key = md5($key ? $key : $GLOBALS['discuz_auth_key']);
	
	    // 密匙a会参与加解密
	    $keya = md5(substr($key, 0, 16));
	    // 密匙b会用来做数据完整性验证
	    $keyb = md5(substr($key, 16, 16));
	    // 密匙c用于变化生成的密文
	    $keyc = $ckey_length ? ($operation == 'DECODE' ? substr($string, 0, $ckey_length): substr(md5(microtime()), -$ckey_length)) : '';
	    // 参与运算的密匙
	    $cryptkey = $keya.md5($keya.$keyc);
	    $key_length = strlen($cryptkey);
	    // 明文，前10位用来保存时间戳，解密时验证数据有效性，10到26位用来保存$keyb(密匙b)，解密时会通过这个密匙验证数据完整性
	    // 如果是解码的话，会从第$ckey_length位开始，因为密文前$ckey_length位保存 动态密匙，以保证解密正确
	    $string = $operation == 'DECODE' ? base64_decode(substr($string, $ckey_length)) : sprintf('%010d', $expiry ? $expiry + time() : 0).substr(md5($string.$keyb), 0, 16).$string;
	    $string_length = strlen($string);
	    $result = '';
	    $box = range(0, 255);
	    $rndkey = array();
	    // 产生密匙簿
	    for($i = 0; $i <= 255; $i++) {
	        $rndkey[$i] = ord($cryptkey[$i % $key_length]);
	    }
	    // 用固定的算法，打乱密匙簿，增加随机性，好像很复杂，实际上并不会增加密文的强度
	    for($j = $i = 0; $i < 256; $i++) {
	        $j = ($j + $box[$i] + $rndkey[$i]) % 256;
	        $tmp = $box[$i];
	        $box[$i] = $box[$j];
	        $box[$j] = $tmp;
	    }
	    // 核心加解密部分
	    for($a = $j = $i = 0; $i < $string_length; $i++) {
	        $a = ($a + 1) % 256;
	        $j = ($j + $box[$a]) % 256;
	        $tmp = $box[$a];
	        $box[$a] = $box[$j];
	        $box[$j] = $tmp;
	        // 从密匙簿得出密匙进行异或，再转成字符
	        $result .= chr(ord($string[$i]) ^ ($box[($box[$a] + $box[$j]) % 256]));
	    }
	    if($operation == 'DECODE') {
	        // substr($result, 0, 10) == 0 验证数据有效性
	        // substr($result, 0, 10) - time() > 0 验证数据有效性
	        // substr($result, 10, 16) == substr(md5(substr($result, 26).$keyb), 0, 16) 验证数据完整性
	        // 验证数据有效性，请看未加密明文的格式
	        if((substr($result, 0, 10) == 0 || substr($result, 0, 10) - time() > 0) && substr($result, 10, 16) == substr(md5(substr($result, 26).$keyb), 0, 16)) {
	            return substr($result, 26);
	        } else {
	            return '';
	        }
	    } else {
	        // 把动态密匙保存在密文里，这也是为什么同样的明文，生产不同密文后能解密的原因
	        // 因为加密后的密文可能是一些特殊字符，复制过程可能会丢失，所以用base64编码
	        return $keyc.str_replace('=', '', base64_encode($result));
	    }
	}
	static public function get($name){
		$query = $_SERVER[QUERY_STRING];
		
		if(empty($name)){
			return "";
		}
		
		$query = explode('&',$query);
		
		$rs = "";
		foreach($query as $k=>$v){
			
			if(!empty($v)){
				$val = explode('=',$v);
				
				if($val[0] == $name){
					
					$rs = $val[1];
				}
			}
		}
		
		return $rs;
	}
	
	public static function is_Date($str,$format="Y-m-d"){
		if(!preg_match('/[0-9]{4}\-[0-9]{1,2}\-[0-9]{1,2}/',$str)) {
			return 0;
		}
		$unixTime_1 = strtotime($str);
		if ( !is_numeric($unixTime_1) || $unixTime_1 <= 0) return 0; //如果非日期，则返回
		$checkDate = date($format, $unixTime_1);
		$unixTime_2 = strtotime($checkDate);;
		if($unixTime_1 == $unixTime_2){
			return 1;
		}else{
			return 0;
		}
	}
	
}